package com.qire.other.push;

import android.app.Application;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;

import com.qire.other.BuildConfig;

import java.util.HashMap;
import java.util.Set;

import androidx.core.app.NotificationManagerCompat;
import cn.jpush.android.api.JPushInterface;

public final class PushManage {

    private static final HashMap<Integer, TagAliasBean> tagAliasActionCache = new HashMap<>();

    private static final Handler HANDLER = new Handler(Looper.myLooper());

    private static int USER_ID;

    private static Application application;

    private PushManage() { }

    public static void init(Application application) {
        JPushInterface.setDebugMode(BuildConfig.DEBUG);
        JPushInterface.init(application);
        PushManage.application = application;
    }

    /**
     * 设置推送别名<br/>
     * 需要理解的是，这个接口是覆盖逻辑，而不是增量逻辑。即新的调用会覆盖之前的设置。
     * init后直接set操作有极大可能导致失败，可能会在回调里拿到6022,6002等，测试的时候可以做个7、8秒的延时，
     * 正式业务里一般配合用户注册使用，延时基本上够用当目标alias下已经有10个设备时，再去尝试绑定可能会报6002,6022，
     * 可以尝试下后台调用我们的服务器删除接口清除下全部绑定关系
     *
     * @param userId
     */
    public static void setAliasToPush(int userId) {
        if(userId < 0 || USER_ID == userId) {
            return;
        }
        USER_ID = userId;

        final TagAliasBean tagAliasBean = new TagAliasBean();
        tagAliasBean.alias = String.valueOf(userId);

        final int sequence = (int) (System.currentTimeMillis() % Integer.MAX_VALUE);

        tagAliasActionCache.put(sequence, tagAliasBean);

        HANDLER.postDelayed(() -> JPushInterface.setAlias(application, sequence, tagAliasBean.alias), 1000);
    }

    /**
     * 如果需要重试某个行为
     * @param sequence 行为序列号，
     */
    public static void retryActionIfNeeded(final int sequence) {
        final TagAliasBean tagAliasBean = tagAliasActionCache.get(sequence);
        if(tagAliasBean != null) {
            HANDLER.postDelayed(() -> JPushInterface.setAlias(application, sequence, tagAliasBean.alias), 1000);
        }
    }

    /**
     * 清楚序列号所表示的标记行为缓存
     * @param sequence
     */
    public static void removeTagAliasActionCacheBy(int sequence) {
        tagAliasActionCache.remove(sequence);
    }

    /**
     * 判断消息通知设置是否启用
     * @param context
     * @return
     */
    public static boolean isNotificationEnabled(Context context) {
        return NotificationManagerCompat.from(context).areNotificationsEnabled();
    }

    public static class TagAliasBean {
        public int action;
        public Set<String> tags;
        public String alias;
        public boolean isAliasAction;

        @Override
        public String toString() {
            return "TagAliasBean{" +
                    "action=" + action +
                    ", tags=" + tags +
                    ", alias='" + alias + '\'' +
                    ", isAliasAction=" + isAliasAction +
                    '}';
        }
    }

}
